<template>
  <div style="height: 100%;">
    <div class="top-header">
      <!--<div class="menu" @click="showMenu = true"><img src="../../../../assets/img/icon-menu.png" alt="" width="100%"></div>-->
      <div class="time">
        <span class="year">{{ time }}</span>
        <span class="week-tag">第{{ nowWeek }}周</span>
      </div>
      <div class="home">
        <router-link to="/myIndex">
          <img src="../../../../assets/img/icon-home.png" alt="" width="100%">
        </router-link>
      </div>
    </div>
    <div class="top-week">
      <div class="week-item" v-for="(item, index) in weeks" :key="index">{{ item }}</div>
    </div>
    <div class="swipe">
      <van-swipe :show-indicators="false" :loop="false" :initial-swipe="swipeIndex" @change="swipeChange" ref="swipe">
        <van-swipe-item v-for="(item, index) in dateArr" :key="index">
          <div class="top-date">
            <div :class="{'date-item': true, 'today': e.isToday}" v-for="(e, i) in item" :key="i">
              <div class="circle">
                <p class="date">{{ e.day }}</p>
                <p class="lunar">{{ e.dayCn }}</p>
              </div>
            </div>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="calendar">
      <div class="course">
        <div v-for="(item, index) in courseList" :key="index" :class="{'row': true, 'first': index === 0}">
          <div class="col first">
            <div class="scale">{{ hours[index].name }}</div>
          </div>
          <div class="col" v-for="i in 7" :key="i">
            <div class="scale" :style="{zIndex: (item && item[i - 1]) ? '2' : '1'}">
              <template v-if="item && item[i - 1]">
                <span
                  class="col-item"
                  v-for="(e, idx) in item[i - 1]"
                  :key="idx"
                  @click.stop="clickSpan(e)"
                  :style="{
                  top: e.top + 'px', height: e.height + 'px',
                  background: e.leave ? '#E5E3E6' : (e.type === 1 ? '#F7D5DA' : '#CFDFF3')
                  }">
                <p class="name">{{ e.name }}</p>
                <p class="clazz-time">{{ e.leave ? '请假' : (e.start + '-' + e.end) }}</p>
              </span>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程查看弹出层 -->
    <van-dialog
      class="close-dialog"
      v-model="showCourse"
      :show-confirm-button="false">
      <van-field v-model="course.kcname" label="课程名称" disabled/>
      <van-field v-model="course.name" label="教师名称" disabled/>
      <van-field v-model="course.time" label="上课时间" disabled/>
      <div class="bottom-btns">
        <van-divider/>
        <div class="bottom-btn">
          <button @click="toAssess">课程报告</button>
        </div>
        <van-divider/>
        <div class="bottom-btn">
          <button v-if="course.register">已签到</button>
          <button v-else @click="toCheck">签到</button>
        </div>
        <van-divider/>
        <div class="bottom-btn">
          <button v-if="course.cstatus">已请假</button>
          <router-link :to="`/leave?id=${course.id}&time=${course.sktime}&name=${course.kcname}`" v-else>
            <button>请假</button>
          </router-link>
        </div>
      </div>
      <div class="close" slot="title" @click="showCourse = false"><img src="../../../../assets/img/icon-close.png" alt=""></div>
    </van-dialog>
  </div>
</template>

<script>
import {getWeekDate, datetimeFormat, getWeekIndexInYear} from '@/utils'
import solarLunar from 'solarlunar'
import api from '@/api'
export default {
  name: 'index2',
  data () {
    return {
      // db type: 1集体，2一对一, leave: 请假
      // db: [
      //   {name: '钢琴课', date: '2019-11-12', start: '10:00', end: '11:00', type: 1},
      //   {name: '古筝课', date: '2019-11-12', start: '14:00', end: '15:00', type: 2, leave: true},
      //   {name: '吉他课', date: '2019-11-13', start: '9:00', end: '10:00', type: 2},
      //   {name: '数学课', date: '2019-11-13', start: '10:40', end: '12:00', type: 1},
      //
      //   {name: '王晓红', date: '2019-11-17', start: '10:40', end: '12:00', type: 2, leave: true},
      //   {name: '集体', date: '2019-11-17', start: '16:00', end: '17:00', type: 1},
      //   {name: '赵六股', date: '2019-11-16', start: '10:40', end: '12:00', type: 2},
      //   {name: '集体', date: '2019-11-16', start: '14:00', end: '16:00', type: 1}
      // ],
      courseList: new Array(19),

      time: '',
      weeks: ['一', '二', '三', '四', '五', '六', '日'],
      hours: [
        {name: '6', value: 6},
        {name: '7', value: 7},
        {name: '8', value: 8},
        {name: '9', value: 9},
        {name: '10', value: 10},
        {name: '11', value: 11},
        {name: '12', value: 12},
        {name: '13', value: 13},
        {name: '14', value: 14},
        {name: '15', value: 15},
        {name: '16', value: 16},
        {name: '17', value: 17},
        {name: '18', value: 18},
        {name: '19', value: 19},
        {name: '20', value: 20},
        {name: '21', value: 21},
        {name: '22', value: 22},
        {name: '23', value: 23},
        {name: '24', value: 24}
      ],
      dates: [],
      dateArr: [],
      showCourse: false,
      course: {
        id: '',
        name: '',
        kcname: '',
        time: '',
        sktime: '',
        cstatus: '',
        register: ''
      },
      swipeIndex: 1,
      target: null,
      cover: null,
      nowWeek: ''
    }
  },
  methods: {
    getCourse (time) {
      let params = {
        // student_id: 40
        student_id: JSON.parse(sessionStorage.getItem('user')).id
      }
      if (time) {
        params.ktime = time[0]
        params.jtime = time[1]
      }
      api.studentCourse({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            let db = []
            res.data.data.forEach(item => {
              let start = datetimeFormat(new Date(Number(item.sktime) * 1000))
              let end = datetimeFormat(new Date(Number(item.xktime) * 1000))
              db.push({
                name: item.kcname,
                date: start.split(' ')[0],
                start: start.split(' ')[1],
                end: end.split(' ')[1],
                type: item.kech,
                leave: item.cstatus === 1,
                id: item.id,
                cstatus: item.cstatus
              })
            })
            this.dbHandle(db)
          } else {
            this.dbHandle([])
          }
        }
      })
    },
    swipeChange (index) {
      this.dates = this.dateArr[index]
      this.nowWeek = getWeekIndexInYear(new Date(this.dates[0].dateStr))
      this.time = `${this.dates[0].dateStr.split('/')[0]}年${this.dates[0].dateStr.split('/')[1]}月`
      setTimeout(() => {
        if (index === 0) {
          // unshift
          this.dateArr.unshift(this.dateArrHandle(getWeekDate(new Date(this.dates[0].dateStr).valueOf() - (24 * 3600 * 1000))))
          this.swipeIndex = 1
        } else if (index === this.dateArr.length - 1) {
          // push
          this.dateArr.push(this.dateArrHandle(getWeekDate(new Date(this.dates[6].dateStr).valueOf() + (24 * 3600 * 1000))))
          this.swipeIndex = index
        }
      }, 500)
      let times = [new Date(this.dates[0].dateStr) / 1000, new Date(this.dates[this.dates.length - 1].dateStr + ' 23:59:59') / 1000]
      this.getCourse(times)
    },

    dateArrHandle (arr) {
      return arr.map((item, index) => {
        let lunar = solarLunar.solar2lunar(item.split('/')[0], item.split('/')[1], item.split('/')[2])
        let dayCn = lunar.dayCn
        if (lunar.isTerm) {
          dayCn = lunar.term
        }
        if (lunar.lDay === 1) {
          dayCn = lunar.monthCn
        }
        return {
          dateStr: item,
          week: this.weeks[index],
          day: item.split('/')[2],
          dayCn,
          isToday: lunar.isToday
        }
      })
    },

    // 点击事件
    clickSpan (clazz) {
      this.course.cstatus = clazz.cstatus
      api.studentCourseDetail({
        params: {
          student_id: JSON.parse(sessionStorage.getItem('user')).id,
          id: clazz.id
        },
        callback: res => {
          if (res.data.error_code === 0) {
            this.course.name = res.data.data.name
            this.course.kcname = res.data.data.kcname
            this.course.id = res.data.data.id
            this.course.sktime = res.data.data.sktime
            this.course.register = res.data.data.register
            let start = datetimeFormat(new Date(Number(res.data.data.sktime) * 1000))
            let end = datetimeFormat(new Date(Number(res.data.data.xktime) * 1000))
            this.course.time = start + '-' + end.split(' ')[1]
            this.showCourse = true
          }
        }
      })
    },
    // 签到
    toCheck () {
      let params = {
        student_id: JSON.parse(sessionStorage.getItem('user')).id,
        id: this.course.id
      }
      api.studentCheckIndex({
        params,
        callback: res => {
          this.$toast({
            message: res.data.message,
            className: 'check-cover',
            position: 'bottom'
          })
        }
      })
    },
    toAssess () {
      // /assessView?id=${course.id}
      api.studentAssess({
        params: {arrangement_id: this.course.id},
        callback: res => {
          if (res.data.data) {
            this.$router.push(`/assessView?id=${this.course.id}`)
          } else {
            this.$toast({
              message: '教师暂未填写报告',
              duration: 2000
            })
          }
        }
      })
    },

    dbHandle (db) {
      let arr = new Array(19)
      db.forEach(item => {
        let week = new Date(item.date).getDay() - 1
        if (week < 0) {
          week = 6
        }
        let hour = Number(item.start.split(':')[0])
        let min = Number(item.start.split(':')[1])

        let endH = Number(item.end.split(':')[0])
        let endM = Number(item.end.split(':')[1])
        let index = hour - 6
        if (!arr[index]) {
          arr[index] = new Array(7)
        }

        item.top = min * 2
        item.height = ((endH - hour) * 60 + (endM - min)) * 2
        if (!arr[index][week]) {
          arr[index][week] = []
        }
        arr[index][week].push(item)
      })
      this.courseList = arr
    }
  },
  created () {
    // this.getCourse()
    const date = new Date()
    this.time = `${date.getFullYear()}年${date.getMonth() + 1}月`

    this.dates = this.dateArrHandle(getWeekDate())
    this.nowWeek = getWeekIndexInYear(new Date(this.dates[0].dateStr))
    this.dateArr = [
      this.dateArrHandle(getWeekDate(new Date(this.dates[0].dateStr).valueOf() - (24 * 3600 * 1000))),
      this.dateArrHandle(getWeekDate()),
      this.dateArrHandle(getWeekDate(new Date(this.dates[6].dateStr).valueOf() + (24 * 3600 * 1000)))
    ]
    let times = [new Date(this.dates[0].dateStr) / 1000, new Date(this.dates[this.dates.length - 1].dateStr + ' 23:59:59') / 1000]
    this.getCourse(times)
  }
}
</script>

<style scoped>
  .top-header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    height: 30px;
  }
  .top-header .time{
    display: flex;
    align-items: center;
  }
  .top-header .time .year{
    font-size: 22px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 30px;
    color: rgba(30,30,30,1);
    margin-right: 16px;
  }
  .top-header .time .week-tag{
    display: inline-block;
    padding: 2px 12px;
    background-color: #E8E8E8;
    border-radius: 20px;
    font-size: 14px;
    font-family: "PingFang SC";
  }
  .top-header .home{
    width: 22px;
    height: 22px;
  }

  .top-week{
    margin-bottom: 16px;
    height: 21px;
  }
  .top-date, .top-week{
    display: flex;
    padding: 0 10px 0 20px;
    background-color: #fff;
  }
  .top-date .date-item, .top-week .week-item{
    flex: 1;
    text-align: center;
    font-weight: bold;
    color: #2D2D2D;
    font-family: PingFangBlod;
  }
  .swipe{
    height: 42px;
    margin-bottom: 10px;
  }
  .date-item .lunar{
    color: #999999;
    font-size: 10px;
  }
  .date-item .circle{
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .date-item.today .circle{
    border: 1px solid #C7DDE5;
  }
  .calendar{
    height: calc(100% - 139px);
    overflow-y: auto;
  }
  .course{
    padding: 10px 10px 0 0;
    background-color: #F2F2F2;
  }
  .course .row{
    height: 60px;
    display: flex;
  }
  .course .row .col{
    flex-grow: 1;
    flex-shrink: 1;
    position: relative;
  }
  .course .row .first{
    width: 20px;
    flex-grow: 0;
    flex-shrink: 0;
    font-size: 24px;
    font-family: PingFangBlod;
    text-align: center;
  }
  .row .col .scale{
    box-sizing: border-box;
    border-right: 1px solid #DFDFDF;
    border-bottom: 1px solid #DFDFDF;
    transform: scale(0.5);
    position: absolute;
    top: -50%;
    left: -50%;
    right: -50%;
    bottom: -50%;
  }
  .row.first .col .scale{
    border-top: 1px solid #DFDFDF;
  }
  .col .scale .col-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: absolute;
    width: 100%;
    background-color: #CFDFF3;
    border: 1px solid #F2F2F2;
    box-sizing: border-box;
  }
  .col-item .name{
    font-size: 24px;
    font-family: PingFangBlod;
    line-height: 36px;
  }
  .col-item .clazz-time{
    font-size: 14px;
  }
  .van-divider{
    margin: 0;
  }
</style>
